package com.abe.libfitness.main;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.abe.libfitness.R;
import com.abe.libfitness.base.BaseComActivity;
import com.abe.libfitness.entity.ComReceiveDataBean;
import com.abe.libfitness.entity.DataEntity;
import com.abe.libfitness.utils.ConstantFitness;
import com.abe.libfitness.utils.ProtocolV3Utils;
import com.abe.libquick.utils.quick.EmptyUtils;
import com.google.gson.Gson;

import java.util.Timer;
import java.util.TimerTask;

public class MotorStartStopActivity extends BaseComActivity {
    //读命令等待时间
    protected int readWaitTime = 10;
    //电机状态
    protected DataEntity dataEntity;
    private boolean motorStart;
    //10秒启动超时计时器相关**************************************************************************
    //计时器（10s读）
    private Timer timer;
    private TimerTask task;
    private int timeOutNum = 0;
    private String actionStr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setDisplay();
    }

    //设置窗口大小
    private void setDisplay() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams p = getWindow().getAttributes();
        p.width = (int) (dm.widthPixels * 0.8);
        getWindow().setAttributes(p);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.item_dialog_loading;
    }

    @Override
    protected void initContent() {
        if (EmptyUtils.isEmpty(bundle()) || !bundle().containsKey(ConstantFitness.START_MOTOR)) {
            finish();
            return;
        }
        resendCount = 3;
        motorStart = bundle().getBoolean(ConstantFitness.START_MOTOR);
        actionStr = motorStart ? "启动" : "停止";
        //启动电机返回成功，发送读电机状态
        builder.append("\n****************************电机:").append(actionStr)
                .append("电机发送成功，解析电机状态\n");
        builderW(ConstantFitness.LOG_FLAG_TEST);
        //开启计时器
        timeOutNum = 0;
        startTimer();
        //电机操作
        motorAction();
    }

    private void motorAction() {
        builder.append("\n****************************电机:").append(actionStr).append("\n");
        builder.append("\n****************************电机命令:")
                .append(new Gson().toJson(ProtocolV3Utils.motorAction(motorStart))).append("\n");
        builderW(ConstantFitness.LOG_FLAG_TEST);
        send(ProtocolV3Utils.motorAction(motorStart));
        getHandler().postDelayed(() -> send(ProtocolV3Utils.motorAction(motorStart)), 100);
        getHandler().postDelayed(() -> send(ProtocolV3Utils.motorAction(motorStart)), 200);
    }

    @Override
    protected void onDataReceived(ComReceiveDataBean ComRecData) {
        wBase("收到:" + json(ComRecData.bRec));
        isCommandRun = false;
        if (resendThread != null) {
            resendThread.stopSend();
            resendThread = null;
        }
        dataEntity = ProtocolV3Utils.parse(ComRecData.bRec);
        if (motorStart) {
            if (dataEntity.getMotorStatus() == ProtocolV3Utils.USR_RUN) {
                builder.append("\n****************************电机:电机正常启动\n");
                setResultOK(new Bundle());
            }
        } else {
            if (dataEntity.getMotorStatus() == ProtocolV3Utils.USR_IDLE) {
                builder.append("\n****************************电机:电机正常停止\n");
                setResultOK(new Bundle());
            }
        }
    }


    private void initTimer() {
        timer = new Timer();
        task = new TimeOutTask();
    }

    //启动计时器
    private void startTimer() {
        /*
         * java.util.Timer.schedule(TimerTask task, long delay, long period)：
         * 这个方法是说，delay/1000秒后执行task,然后进过period/1000秒再次执行task，
         * 这个用于循环任务，执行无数次，当然，你可以用timer.cancel();取消计时器的执行。
         */
        initTimer();
        try {
            timer.schedule(task, 1000, 1000);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            initTimer();
            timer.schedule(task, 1000, 1000);
        }
    }

    private void autoStopTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
        //置零
        timeOutNum = 0;
    }

    private void destroyTimer() {
        timer = null;
        task = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当activity不在前台是停止定时
        stopTimer();
    }

    @Override
    public void onDestroy() {
        //销毁时停止定时
        stopTimer();
        destroyTimer();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {

    }

    protected class TimeOutTask extends TimerTask {

        @Override
        public void run() {
            timeOutNum++;
            if (timeOutNum >= readWaitTime) {
                autoStopTimer();
                boolean success = false;
                if (EmptyUtils.isNotEmpty(dataEntity)) {
                    if (motorStart) {
                        success = dataEntity.getMotorStatus() == ProtocolV3Utils.USR_RUN;
                        toast(success ? R.string.motor_start_success : R.string.motor_start_fail);
                    } else {
                        success = dataEntity.getMotorStatus() == ProtocolV3Utils.USR_IDLE;
                        toast(success ? R.string.motor_stop_success : R.string.motor_stop_fail);
                    }
                } else {
                    toast(motorStart ? R.string.motor_start_fail : R.string.motor_stop_fail);
                }
                builder.append("\n****************************电机:电机").append(actionStr)
                        .append(success ? "成功" : "失败").append("\n");
                builderW(ConstantFitness.LOG_FLAG_TEST);
                if (success) setResultOK(new Bundle());
                else setResultCancel();
            } else {
                if (timeOutNum == 3 || timeOutNum == 6 || timeOutNum == 9) {
                    if (EmptyUtils.isNotEmpty(dataEntity)) {
                        if (dataEntity.getMotorStatus() != ProtocolV3Utils.USR_RUN) {
                            motorAction();
                        }
                    } else {
                        motorAction();
                    }
                }
            }
        }
    }
}